package com.bsj.sipgateway.sip.transmit.callback;

import com.alibaba.fastjson.JSON;
import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.sipgateway.command.RocketMqCommand;
import com.bsj.sipgateway.common.constant.Constants;
import com.bsj.sipgateway.common.def.RecordFile;
import com.bsj.sipgateway.common.def.RecordList;
import com.bsj.sipgateway.mq.producer.CommandUpProducer;
import com.bsj.sipgateway.sip.session.CommandManager;
import com.bsj.sipgateway.sip.transmit.request.impl.MessageRequestProcessor;
import com.bsj.sipgateway.util.RecordInfoUtil;
import com.bsj.sipgateway.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import redis.clients.bsj.JedisClusterBSJ;
import redis.clients.jedis.Jedis;

import java.util.Comparator;

@SuppressWarnings("unchecked")
@Slf4j
public class CheckForAllRecordsThread extends Thread {

    //缓存的key， deviceId_sn       //查询录像资源的deviceId乱传，不能作为key，改用"RecordInfo"+sn
    private String key;

    //总数量
    private int total;

    // redis
    JedisClusterBSJ jedisClusterBSJ;

    String channelId;

    public CheckForAllRecordsThread(String key, int total, JedisClusterBSJ jedisClusterBSJ, String channelId) {
        this.key = key;
        this.total = total;
        this.jedisClusterBSJ = jedisClusterBSJ;
        this.channelId = channelId;
    }

    public void run() {
        try {
            RecordList recordList = null;
            //如果超过10秒，还没完成的就直接响应mq
            for (int i = 1; i <= 10; i++) {
                recordList = MessageRequestProcessor.recordListMap.get(key);
                if (recordList == null) {
                    break;
                }
                int receiveSize = recordList.getRecordFileSize();
                if (receiveSize < total) {
                    log.info("已获取" + receiveSize + "项录像数据，共" + total + "项");
                } else {
                    log.info("录像数据已全部获取，共" + total + "项");

                    break;
                }
                Thread.sleep(1000);
            }
            if (recordList != null) {
                // 按时间升序排序
                recordList.getListFile().sort(Comparator.comparing(RecordFile::getBegintime));
                CommandManager.remove(key);
            }
            // todo 存入缓存带过期时间
            RecordInfoUtil.saveRecordInfoToRds(channelId, recordList, jedisClusterBSJ, 600);

            //清除缓存
            MessageRequestProcessor.recordListMap.remove(key);
        } catch (Exception e) {
            //清除缓存
            MessageRequestProcessor.recordListMap.remove(key);
            log.error("线程统计已获取录像文件数量异常", e);
        }

    }


}
